package com.demo.config;

import com.demo.interceptor.LoginInterceptor;
import com.demo.interceptor.RefreshTokenInterceptor;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import javax.annotation.Resource;

import static com.demo.utils.SystemConstants.MaxAge;
import static com.demo.utils.SystemConstants.UPLOAD_ABSOLUTE_PATH;

@Configuration
public class MvcConfig implements WebMvcConfigurer {
    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        // token刷新的拦截器
        registry.addInterceptor(new RefreshTokenInterceptor(stringRedisTemplate)).addPathPatterns("/**").order(0);

        // 用户登录拦截器
        registry.addInterceptor(new LoginInterceptor())
                .excludePathPatterns(
                        "/**/common/**",
                        // 文档
                        "/doc.html"
                )
                .excludePathPatterns("/upload/**","/swagger-resources/**", "/webjars/**", "/v2/**", "/swagger-ui.html/**")
                .order(1);
    }

    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")
                .allowedOrigins("*")
                .allowedMethods("POST", "GET", "PUT", "OPTIONS", "DELETE")
                .maxAge(MaxAge)
                .allowCredentials(true);
    }

    /***
     * 配置静态资源访问拦截
     */
    public void addResourceHandlers(ResourceHandlerRegistry registry){
        registry.addResourceHandler("swagger-ui.html")
                .addResourceLocations("classpath:/META-INF/resources/");

        registry.addResourceHandler("/upload/**")
                .addResourceLocations("file:///" + UPLOAD_ABSOLUTE_PATH);
    }
}
